app.controller("configCtrl", ["$scope", "$http", "$filter", "$rootScope", "$stateParams", "$timeout", "$modal", "lodash",
function($scope, $http, $filter, $rootScope, $stateParams, $timeout, $modal, lodash) {
    $rootScope.initBreadcrumb($scope.breadcrumb);
    $rootScope.initHeaderElements($scope.settings);
    $scope.breadcrumb.push('区域管理');

    $scope.settings.searchEle = {
        show: true, //显示查询框
        func: function (keyword) {
            seachConfig(keyword);
        },
        blurFunc: function (keyword) {
            seachConfig(keyword);
        }
    };
    var addConfig = {
        show: $rootScope.isMatrixRole(),
        label: "新建",
        func: function () {
            addConfigItem();
        }
    };
    $scope.settings.btnEle.push(addConfig);

    $scope.info = {
        // 原始区域数据
        originConfigArray: [
            {"id": "1", "name": "cwm1.0", "type": "tomcat01", "url": "", "order": "1", "fileList": [], "portList": [], "areaList": []},
            {"id": "2", "name": "cwm2.0", "type": "tomcat02", "url": "172.168.1.1", "order": "2", "fileList": [], "portList": [], "areaList": []},
            {"id": "3", "name": "cwm3.0", "type": "tomcat03", "url": "", "order": "3", "fileList": [], "portList": [], "areaList": []},
            {"id": "4", "name": "cwm4.0", "type": "tomcat04", "url": "172.168.1.1", "order": "4", "fileList": [], "portList": [], "areaList": []},
            {"id": "5", "name": "cwm5.0", "type": "tomcat05", "url": "", "order": "5", "fileList": [], "portList": [], "areaList": []},
            {"id": "6", "name": "cwm6.0", "type": "tomcat06", "url": "172.168.1.1", "order": "6", "fileList": [], "portList": [], "areaList": []}
        ],
        originConfigTypeArray: [
            {"key": "tomcat01", "value": "tomcat-dubbo-01"},
            {"key": "tomcat02", "value": "tomcat-dubbo-02"},
            {"key": "tomcat03", "value": "tomcat-dubbo-03"},
            {"key": "tomcat04", "value": "tomcat-dubbo-04"},
            {"key": "tomcat05", "value": "tomcat-dubbo-05"},
            {"key": "tomcat06", "value": "tomcat-dubbo-06"}
        ],
        configList: [],
    };

    //设置data-table
    $scope.options = {
        rowHeight: 40,
        headerHeight: 40,
        footerHeight: 50,
        columnMode: 'force',
        forceFillColumns: true,
        emptyMessage: '暂无数据！',
        columns: [
            { name: "应用名称", width: 100, prop: 'name'},
            { name: "应用类型", width: 100, prop: 'typeName'},
            { name: "应用地址", width: 80, prop: 'url'},
            { name: "启动顺序", width: 80, prop: 'order'},
            {
                name: "配置",
                width: 100,
                cellRenderer: function () {
                    return '<a href="javascript:void(0);" style="margin-right: 10px;" ng-click="updateItem($row)">修改</a>' +
                           '<a href="javascript:void(0);" style="margin-right: 10px;" ng-click="gotoBeetle()">维护配置</a>' +
                           '<a href="javascript:void(0);" ng-click="deleteItem($row)">删除</a>';
                }
            }
        ],
    };

    setTableData();

    // 获取区域数据
    function setTableData() {
        $timeout(function() {
            angular.forEach($scope.info.originConfigArray, function(config) {
                var filterConfigItem = lodash.findWhere($scope.info.originConfigTypeArray, {key: config.type});
                config.typeName = filterConfigItem ? filterConfigItem.value : config.type;
                config.url = config.url || "-";
            });
            $scope.tableData = $scope.info.originConfigArray;
        }, 200);
    }

    // 查询
    function seachConfig(keyword) {
        var searchConfigData = new Array();
        angular.forEach($scope.info.originConfigArray, function(item) {
            if(item.name == keyword || item.typeName == keyword || item.url == keyword || item.order == keyword) {
                searchConfigData.push(item);
            }
        });
        $scope.tableData = searchConfigData.length ? searchConfigData : $scope.info.originConfigArray;
    };

    // 新建
    function addConfigItem() {
        openModal("add");
    };

    // 修改
    $scope.updateItem = function(row) {
        openModal("update", row);
    };

    // 打开modal
    function openModal(type, row) {
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/ucloud2.0/tpl/configModal.html"),
            controller: "configModalCtrl",
            keyboard: true,
            backdrop: true,
            resolve: {
                type: function () {
                    return type;
                },
                row: function() {
                    return row;
                },
                typeData: function() {
                    return $scope.info.originConfigTypeArray;
                }
            }
        });

        modalInstance.result.then(function (configItem) {
            ajaxFun(configItem);
        }, function (reason) {
            console.log("关闭modal");
        });
    };
        
    // 更新数据
    function ajaxFun(configItem) {
        if(!configItem.id) {
            // 新增
            configItem.id = $scope.info.originConfigArray.length + 1;
            $scope.info.originConfigArray.push(configItem);
            $scope.tableData = $scope.info.originConfigArray;
        } else {
            // 修改
            var updateItem = lodash.findWhere($scope.info.originConfigArray, {id: configItem.id});
            updateItem.name = configItem.name;
            updateItem.type = configItem.type;
            updateItem.typeName = configItem.typeName;
            updateItem.url = configItem.url;
            updateItem.order = configItem.order;
            updateItem.fileList = configItem.fileList;
            updateItem.portList = configItem.portList;
            updateItem.areaList = configItem.areaList;
        }
        $rootScope.toasterSuccessInfo("操作成功！");
    };

    // 跳转beetle配置文件页面
    $scope.gotoBeetle = function() {
        window.open(beetle_ui_url + "#/menu/configFile////true");
    };

    // 删除
    $scope.deleteItem = function(row) {
        var confirm = {
            titleData: "提示",
            bodyData: "确定要删除应用配置【"+ row.name +"】吗？"
        };
        $rootScope.confirmWindow(confirm, function (data) {
            if(data){
                lodash.remove($scope.info.originConfigArray, {id: row.id});
                $scope.tableData = $scope.info.originConfigArray;
                $rootScope.toasterSuccessInfo("删除成功！");
            }
        })
    };

}]);

app.controller("configModalCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "lodash", "type", "row", "typeData", function ($scope, $rootScope, $modalInstance, $http, lodash, type, row, typeData) {
    $scope.info = {
        configTitle: type == "add" ? "添加应用配置" : "修改应用配置",
        configName: "",                         // 配置名称
        configTypeList: [],                     // 配置类型数据
        sltConfigTypeItem: "",                  // 选中的配置类型数据
        configUrl: "",                          // 配置url
        configOrder: 0,                         // 配置顺序
        configSearchUrl: "main/src/resource/",  // 默认配置路径
        showConfigFileList: false,              // 根据配置路径，显示查找出来的结果
        configFileArray: [],                    // 配置路径下的配置文件数据（查询出来的数据）
        sltConfigFileItem: "",                  // 选中的配置文件数据
        configAreaList: [],                     // 全部区域数据
        configSelectAreaList: "",               // 选中的区域
        configFileList: [],                     // 应用数据包含的file数据
        configPortList: [],                     // 应用数据包含的port数据
        selectFileList: [],                     // 已经选择的file数据
        leftPortValue: "",                      // port左侧数据
        rightPortValue: "",                     // port右侧数据
        originConfigFileList: [
            {"id": "1", "name": "config.js"},
            {"id": "2", "name": "config-data.js"},
            {"id": "3", "name": "config-mock-data.js"},
            {"id": "4", "name": "application.propotery"}
        ],
    }

    initConfigDetails();

    // 初始化config信息
    function initConfigDetails() {
        // 设置应用类型
        angular.forEach(typeData, function(type) {
            type.crtname = type.value;
        });
        $scope.info.configTypeList = typeData;
        // 设置区域数据（4大区+小区）
        var allAreaList = new Array();
        angular.forEach(config_area_list, function(area) {
            allAreaList.push(area);
            angular.forEach(config_warehouse_list, function(warehouse) {
                if(area.areaName == warehouse.type) {
                    allAreaList.push(warehouse);
                }
            });
        });
        $scope.info.configAreaList = allAreaList;
        // 设置配置文件数据
        $scope.info.configFileList = type == "add" ? [] : row.fileList;
        // 设置端口数据
        $scope.info.configPortList = type == "add" ? [] : row.portList;
        // 设置应用名称
        $scope.info.configName = type == "add" ? "" : row.name;
        // 设置应用类型
        $scope.info.sltConfigTypeItem = type == "add" ? "" : lodash.findWhere($scope.info.configTypeList, {key: row.type});
        // 设置应用名称
        $scope.info.configUrl = type == "add" ? "" : row.url;
        // 设置应用顺序
        $scope.info.configOrder = type == "add" ? 0 : row.order;
        // 设置选中区域
        $scope.info.configSelectAreaList = type == "add" ? [] : row.areaList;
    };

    // 查找
    $scope.searchFileByUrl = function() {
        if(!$scope.info.configSearchUrl) {
            $rootScope.toasterWarningInfo("请输入配置文件路径！");
            return false;
        }
        $scope.info.showConfigFileList = true;
        // 设置配置文件数据（根据配置路径查出来的数据）
        angular.forEach($scope.info.originConfigFileList, function(file) {
            file.crtname = file.name;
        });
        $scope.info.configFileArray = $scope.info.originConfigFileList;
    };

    // 添加config配置文件
    $scope.addConfigFile = function() {
        $scope.info.configFileList.push($scope.info.sltConfigFileItem);
        lodash.remove($scope.info.configFileArray, {name: $scope.info.sltConfigFileItem.name});
    };

    // 删除file文件
    $scope.removeFile = function(file) {
        lodash.remove($scope.info.configFileList, {name: file.name});
        $scope.info.configFileArray.push(file);
    };

    // 添加端口
    $scope.addPort = function() {
        if(!$scope.info.leftPortValue || !$scope.info.rightPortValue) {
            $rootScope.toasterWarningInfo("请输入端口！");
            return false;
        }
        if($scope.info.leftPortValue <= 999 || $scope.info.rightPortValue <= 999) {
            $rootScope.toasterWarningInfo("请输入正确格式的端口！");
            return false;
        }
        var newPortItem = {
            "id": $scope.info.configPortList.length + 1,
            "leftValue": $scope.info.leftPortValue,
            "rightValue": $scope.info.rightPortValue
        };
        $scope.info.configPortList.push(newPortItem);
    };

    // 删除端口
    $scope.removePort = function(port) {
        lodash.remove($scope.info.configPortList, {id: port.id});
    };

    $scope.createClick = function () {
        if(!$scope.info.configName) {
            $rootScope.toasterWarningInfo("请输入应用名称！");
            return false;
        }
        if(!$scope.info.sltConfigTypeItem) {
            $rootScope.toasterWarningInfo("请选择应用类型！");
            return false;
        }
        if(!$scope.info.configUrl) {
            $rootScope.toasterWarningInfo("请输入应用地址！");
            return false;
        }
        if(!$scope.info.configOrder) {
            $rootScope.toasterWarningInfo("请输入应用顺序！");
            return false;
        }
        var configItem = {
            "id": type == "add" ? "" : row.id,
            "name": $scope.info.configName,
            "type": $scope.info.sltConfigTypeItem.key,
            "typeName": $scope.info.sltConfigTypeItem.value,
            "url": $scope.info.configUrl,
            "order": $scope.info.configOrder,
            "fileList": $scope.info.configFileList,
            "portList": $scope.info.configPortList,
            "areaList": $scope.info.configSelectAreaList
        };
        $modalInstance.close(configItem);
    };

    $scope.cancelClick = function () {
        $modalInstance.dismiss("cancel");
    };
}]);
